<script setup>
import { onMounted, ref } from 'vue';
import {ElMessageBox, ElMessage } from "element-plus";
// 搜索详情
const searchInfo = ref({ name: '', accout: '', status: '', scale: '', })
// 量表信息 - 分为8大类
const scales = ref([
    // 1.1 心理健康
    { value: 1, name: '抑郁自评量表（SDS）', group: '1.1 心理健康' },
    { value: 2, name: '焦虑自评量表（SAS）', group: '1.1 心理健康' },
    { value: 3, name: '青少年生活事件量表', group: '1.1 心理健康' },
    { value: 4, name: 'SCL-90症状自评量表', group: '1.1 心理健康' },
    { value: 5, name: '情绪自评量表（DASS-21）', group: '1.1 心理健康' },
    { value: 6, name: '青春期性心理健康量表', group: '1.1 心理健康' },
    
    // 1.2 职业选择
    { value: 7, name: 'MBTI性格类型测试问卷', group: '1.2 职业选择' },
    { value: 8, name: '霍兰德职业倾向测验量表', group: '1.2 职业选择' },
    
    // 1.3 学习心理
    { value: 9, name: '认知灵活性问卷', group: '1.3 学习心理' },
    { value: 10, name: '学习沉醉感量表', group: '1.3 学习心理' },
    { value: 11, name: '时间管理自我监控量表', group: '1.3 学习心理' },
    { value: 12, name: '创造性倾向问卷', group: '1.3 学习心理' },
    { value: 13, name: '考试心理和行为问题症状自评量表', group: '1.3 学习心理' },
    { value: 14, name: '学习倦怠量表', group: '1.3 学习心理' },
    
    // 1.4 学校文化
    { value: 15, name: '师生关系量表', group: '1.4 学校文化' },
    { value: 16, name: '青少年学生生活满意度量表', group: '1.4 学校文化' },
    
    // 1.5 恋爱关系
    { value: 17, name: '恋爱心理压力源量表', group: '1.5 恋爱关系' },
    { value: 18, name: '斯腾伯格爱情量表', group: '1.5 恋爱关系' },
    
    // 1.6 人格特质
    { value: 19, name: '心理韧性量表', group: '1.6 人格特质' },
    { value: 20, name: '自我认同感量表', group: '1.6 人格特质' },
    { value: 21, name: '大五人格量表简化版', group: '1.6 人格特质' },
    { value: 22, name: '艾森克人格问卷（EPQ）', group: '1.6 人格特质' },
    { value: 23, name: '情商测试量表', group: '1.6 人格特质' },
    { value: 24, name: '卡特尔16种性格因素人格测验', group: '1.6 人格特质' },
    { value: 25, name: 'Rosenberg自尊量表', group: '1.6 人格特质' },
    
    // 1.7 家庭关系
    { value: 26, name: '家庭亲合量表', group: '1.7 家庭关系' },
    { value: 27, name: '社会支持评定量表', group: '1.7 家庭关系' },
    { value: 28, name: '父母教养方式问卷', group: '1.7 家庭关系' },
    { value: 29, name: '双元孝道信念量表', group: '1.7 家庭关系' },
    
    // 1.8 人际关系
    { value: 30, name: '人际关系综合诊断量表', group: '1.8 人际关系' },
    { value: 31, name: '社交焦虑量表', group: '1.8 人际关系' },
    { value: 32, name: '人际信任量表（ITS）', group: '1.8 人际关系' },
])
// 评测状态
const conditions = ref([
    { value: 1, name: '全部' },
    { value: 2, name: '已完成' },
    { value: 3, name: '未完成' },
])
// 完整表格数据
const tableData = ref([
  {
    id: 1,
    name: '李明',
    account: 'LM20250902',
    scale: 1, // 抑郁自评量表（SDS）- 心理健康类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 2,
    name: 'Tom',
    account: 'Tom20250902',
    scale: 7, // MBTI性格类型测试问卷 - 职业选择类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 3,
    name: '张三',
    account: 'ZS20250902',
    scale: 9, // 认知灵活性问卷 - 学习心理类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 4,
    name: '李四',
    account: 'LS20250902',
    scale: 15, // 师生关系量表 - 学校文化类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 5,
    name: '王五',
    account: 'WW20250902',
    scale: 17, // 恋爱心理压力源量表 - 恋爱关系类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 6,
    name: '赵六',
    account: 'ZL20250902',
    scale: 19, // 心理韧性量表 - 人格特质类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 7,
    name: '孙七',
    account: 'SQ20250902',
    scale: 26, // 家庭亲合量表 - 家庭关系类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 8,
    name: '周八',
    account: 'ZB20250902',
    scale: 30, // 人际关系综合诊断量表 - 人际关系类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 9,
    name: '吴九',
    account: 'WJ20250902',
    scale: 2, // 焦虑自评量表（SAS）- 心理健康类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 10,
    name: '郑十',
    account: 'ZS20250902',
    scale: 8, // 霍兰德职业倾向测验量表 - 职业选择类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 11,
    name: '钱十一',
    account: 'QSY20250902',
    scale: 10, // 学习沉醉感量表 - 学习心理类
    status: 3,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 12,
    name: '孙十二',
    account: 'SSY20250902',
    scale: 16, // 青少年学生生活满意度量表 - 学校文化类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },
  {
    id: 13,
    name: '李十三',
    account: 'LS20250902',
    scale: 18, // 斯腾伯格爱情量表 - 恋爱关系类
    status: 2,
    useTime: 300,
    beginTime: '2025-9-16 07:45:15',
    endTime: '2025-9-16 07:50:15',
  },

])
// tableData的复制品
const tableDataCopy = ref([])
// 当前表格数据
const currentTableData = ref([])
// 当前pageSize
const currentPageSize = ref(10)
// 当前页
const currentPage = ref(1)

// 按group属性将量表数据分组
const getGroupedScales = () => {
  const groups = {}
  
  // 遍历所有量表，按group属性分组
  scales.value.forEach(scale => {
    if (!groups[scale.group]) {
      groups[scale.group] = []
    }
    groups[scale.group].push(scale)
  })
  
  // 转换为el-option-group需要的格式
  return Object.keys(groups).map(groupName => ({
    label: groupName,
    options: groups[groupName]
  }))
}

// 获取评测量表名称
const getScaleName = (scaleValue) => {
    for (const scale of scales.value) {
        if (scale.value == scaleValue) return scale.name
    }
}
// 当pageSize变化时
const handleSizeChange = (newPageSize) => {
    currentTableData.value = tableData.value.slice(0, newPageSize)
}
// 当页面改变时
const handleCurrentChange = (newPage) => {
    const start = (newPage - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    currentTableData.value = tableData.value.slice(start, end)
}
// 搜索 - 模糊搜索实现
const search = () => {
    tableData.value = []
    
    // 获取搜索关键词并转为小写用于不区分大小写的搜索
    const searchName = searchInfo.value.name.toLowerCase()
    const searchAccount = searchInfo.value.accout.toLowerCase()
    
    for (let index = 0; index < tableDataCopy.value.length; index++) {
        const item = tableDataCopy.value[index]
        
        // 如果搜索关键词不为空，则进行模糊搜索匹配
        if (searchInfo.value.name && !item.name.toLowerCase().includes(searchName)) continue
        if (searchInfo.value.accout && !item.account.toLowerCase().includes(searchAccount)) continue
        if (searchInfo.value.status && searchInfo.value.status != 1 && searchInfo.value.status != item.status) continue
        if (searchInfo.value.scale && searchInfo.value.scale != item.scale) continue
        
        tableData.value.push(item)
    }
    
    currentPage.value = 1
    currentTableData.value = tableData.value.slice(0, currentPageSize.value)
}
// 重置
const reset = () => {
    searchInfo.value = { name: '', accout: '', status: '', scale: '', }
    tableData.value = tableDataCopy.value
    search()
}
// 删除记录
const deleRecord = (row) => {
  ElMessageBox.confirm(`确定删除用户 "${row.name}" 的 "${getScaleName(row.scale)}" 测评记录吗？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 1. 从 tableData 中删除该条数据
    const index = tableData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      tableData.value.splice(index, 1);
    }

    // 2. 同步更新 tableDataCopy（用于重置）
    const copyIndex = tableDataCopy.value.findIndex(item => item.id === row.id);
    if (copyIndex !== -1) {
      tableDataCopy.value.splice(copyIndex, 1);
    }

    // 3. 重新计算当前页数据
    handleCurrentChange(currentPage.value);

    ElMessage.success('删除成功');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

onMounted(() => {
    currentTableData.value = tableData.value.slice(0, 10)
    tableDataCopy.value = tableData.value
})
</script>

<template>
<div class="search-box">
    <!-- 搜索部分 -->
    <el-row>
        <el-col :span="4"></el-col>
        <el-col :span="4">
        <el-select v-model="searchInfo.scale" placeholder="请选择量表" style="width: 200px" group-key="group" group-label="group">
            <el-option-group
              v-for="group in getGroupedScales()"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="scale in group.options"
                :key="scale.value"
                :label="scale.name"
                :value="scale.value"
              />
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="4">
            <el-select v-model="searchInfo.status" placeholder="请选择评测状态" style="width: 200px">
                <el-option v-for="condition in conditions" :key="condition.value" :label="condition.name" :value="condition.value"/>
            </el-select>
        </el-col>
        <el-col :span="4"><el-input v-model="searchInfo.name" style="width: 200px" placeholder="请输入姓名" /></el-col>
        <el-col :span="4"><el-input v-model="searchInfo.accout" style="width: 200px" placeholder="请输入账号" /></el-col>
        <el-col :span="4">
            <el-button type="primary" @click="search"><el-icon><Search /></el-icon>&nbsp;查询</el-button>
            <el-button type="primary" @click="reset"><el-icon><Remove /></el-icon>&nbsp;重置</el-button>
        </el-col>
    </el-row>
</div>
<!-- 表格部分 -->
<div class="table-box">
    <el-table :data="currentTableData" style="width: 100%" :header-cell-style="{ 'background-color': '#f5f7fa' }" height="450px">
        <el-table-column fixed prop="id" label="序号" min-width="100" />
        <el-table-column prop="name" label="姓名" min-width="150" />
        <el-table-column prop="account" label="账号" min-width="150" />
        <el-table-column label="量表名称" min-width="180" >
            <template #default="scope">
                {{ getScaleName(scope.row.scale) }}
            </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100" >
            <template #default="scope">
                <span :style="{ 'color': scope.row.status == 2 ? '#606266' : 'red' }">{{ scope.row.status == 1 ? '已完成' : '未完成' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="useTime" label="答题时长" min-width="120" />
        <el-table-column prop="beginTime" label="开始时间" min-width="150" />
        <el-table-column prop="endTime" label="完成时间" min-width="150" />
        <el-table-column fixed="right" label="操作" min-width="100" >
            <template #default="scope">
                <el-button link type="danger" size="small" @click="deleRecord(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</div>
<div class="page-box">
     <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</div>
</template>

<style scoped>
.search-box {
    padding: 10px 0px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}
</style>
